package com.beiyou.servlet;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.*;

//@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
    private String message;

    //private String str;
    public void init() {
        message = "Hello World!中文效果";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        response.setHeader("Content-Type", "text/html;charset=utf-8");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //InputStream输入流 输入这个内容
        ServletInputStream inputStream = req.getInputStream();
        //实例化InputStreamReader 读取
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        //实例化BuffereReader 缓冲数据并读取
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String jsonStr = "";
        String line;
        while ((line = bufferedReader.readLine()) !=null){
                jsonStr += line;
        }
       //jsonStr转换

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        JSONObject jsonObject1 = new JSONObject();
        //成功时返回的格式
        jsonObject1.put("code",0);
        jsonObject1.put("date",jsonObject);
        jsonObject1.put("message","发送成功");
        //失败时返回的格式
        //jsonObject1.put("code",1);
        //jsonObject1.put("date",null);
        //jsonObject1.put("message","发送失败");

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().write(String.valueOf(jsonObject1));

        //PrintWriter writer = resp.getWriter();
        //writer.println("<html>");
        //writer.println("<body>");
        //writer.println("id:" + jsonObject.getString("id"));
        //writer.println("<br/>");
        //writer.println("name:" + jsonObject.getString("name"));
        //writer.println("</body>");
        //writer.println("</html>");

    }

    public void destroy() {
    }
}